﻿using System.Collections.ObjectModel;
using System.Linq;
using Workbench.Models;
using Workbench.Shared;

namespace Workbench.Presentation
{
    public class FileSelectViewModel : ViewModelBase
    {
        private ObservableCollection<ProjectFileViewModel> availableFiles = new ObservableCollection<ProjectFileViewModel>();
        public ObservableCollection<ProjectFileViewModel> AvailableFiles { get { return availableFiles; } }

        private ProjectFileViewModel selectedFile;
        public ProjectFileViewModel SelectedFile
        {
            get { return selectedFile; }
            set
            {
                if (selectedFile != value)
                {
                    selectedFile = value;
                    RaisePropertyChanged();
                }
            }
        }

        public FileSelectViewModel()
        {
            AvailableFiles.SubscribeItemPropChange("IsSelected", AvailableFiles_IsSelectedChanged);
        }

        private void AvailableFiles_IsSelectedChanged(ProjectFileViewModel fileViewModel)
        {
            if (fileViewModel.IsSelected)
            {
                SelectedFile = fileViewModel;
            }
        }

        public void Unload()
        {
            AvailableFiles.Clear();
            SelectedFile = null;
        }

        public void ShowFiles(ProjectDirectoryModel rootDirectory)
        {
            var fileViewModels = rootDirectory.GetContextIncludedFiles()
                                            .Select(x => new ProjectFileViewModel(x));
            AvailableFiles.Clear();
            AvailableFiles.AddRange(fileViewModels);
        }
    }
}
